package com.mayikt.days03;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName MayijtExecutor
 * @Author 蚂蚁课堂余胜军 QQ644064779 www.mayikt.com
 * @Version V1.0
 **/
public class MayiktExecutor {
    /**
     * 存放我们提交任务的线程
     */
    private BlockingQueue<Runnable> runnables;
    /**
     * 一直正在运行的线程 核心线程数
     */
    private List<TaskThread> taskThreads;
    private volatile boolean flag = true;

    public MayiktExecutor(int coreThreads, int queueSize) {
        taskThreads = new ArrayList<TaskThread>(coreThreads);
        runnables = new LinkedBlockingQueue<>(queueSize);
        for (int i = 0; i < coreThreads; i++) {
            TaskThread taskThread = new TaskThread();
            taskThread.start();
            taskThreads.add(taskThread);
        }

    }


    class TaskThread extends Thread {
        @Override
        public void run() {
            while (runnables.size() > 0 || flag) {
                Runnable runnable = runnables.poll();
                if (runnable != null) {
                    runnable.run();
                }
            }
        }
    }

    public void executor(Runnable runnable) {
        try {
            runnables.offer(runnable, 1, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        MayiktExecutor mayiktExecutor = new MayiktExecutor(2, 12);
        //有两个线程
        for (int i = 0; i < 10; i++) {
            int finalI = i;
            mayiktExecutor.executor(() -> System.out.println(Thread.currentThread().getName() + "," + finalI));
        }
        mayiktExecutor.flag = false;
        // 10次循环非常快 前面两个线程已经装入成功了，但是没有立马消费，
    }
}
